<script>
import dayjs from 'dayjs'
import { saveReactionExam, getReactionExam } from '@/pages/game/api'
export default {
  props: {
    name: {
      type: String,
      default: 'game'
    }
  },
  data() {
    return {
      now: null,
      timer: null,
      groupId: '',
      lastTime: null
    }
  },
  computed: {
    duration() {
      if (!this.now) {
        return
      }
      return this.now.format('HH:mm:ss')
    }
  },
  mounted() {
    console.log('timer mounted')
    this.groupId = dayjs().startOf('week').add(1, 'day').format('YYYYMMDD')
    this.getLastMinutes()
  },
  destroyed() {
    console.log('timer destroyed')
    this.onBeforeRouteLeave()
    this.timer && clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    getLastMinutes() {
      getReactionExam({ groupId: this.name + this.groupId }).then(res => {
        this.lastTime = dayjs().startOf('day').add(res || 0, 'minute')
        this.$emit('lastTimeChange', this.lastTime)
        this.now = dayjs(this.lastTime.valueOf())
        this.interval()
      })
    },
    interval() {
      this.timer = setInterval(() => {
        this.now = this.now.add(1, 's')
      }, 1000)
    },
    async onBeforeRouteLeave() {
      const duration = this.now.diff(this.lastTime, 'm', true).toFixed()
      console.log('before router leave')
      await saveReactionExam({
        duration,
        groupId: this.name + this.groupId
      })
    }
  }
}
</script>

<template>
  <div class="g-timer">
    <!-- <span class="g-timer__label">时长: </span> -->
    <span>{{ duration }}</span>
  </div>
</template>

<style lang="less">
.g-timer {
  flex-shrink: 0;
  position: relative;
  display: flex;
  align-items: center;
  font-size: 40px;
  font-family: 'Courier New', Courier, monospace;
  &__label {
    width: 90px;
  }
}
</style>
